// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: 's-web-devin-3gvwv5vda1185f99' }) // 使用当前云环境

const db = cloud.database();

const updateGoodsNumber = async ({ _id, msg }) => {
  // 1. 查询商品表中的数据，拿到之后，更新数量
  const goods = await db.collection('goods').where({ _id }).get()
  console.log('goods:', goods)
  if (msg === 'add') {
    goods.data[0].number++
  } else if (msg === 'reduce') {
    goods.data[0].number--
  }
  let response;
  if (goods.data[0].number >= 1) {
    console.log('商品添加', goods.data[0].number)
    response = await db.collection('goods').doc(_id)
      .update({
        data: {
          // inc 直接批量递增
          number: goods.data[0].number,
          isCart: true // 是否在购物车中
        }
      })
    console.log('更新后的结果:', response)
  } else {
    response = await db.collection('goods').doc(_id)
      .update({
        data: {
          // inc 直接批量递增
          number: goods.data[0].number,
          isCart: false
        }
      })
  }
  console.log('最终结果:', response)
  return response;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { _id, msg = 'add', } = event;
  const response = await updateGoodsNumber({ _id, msg })
  console.log('response:--------------', response)
  return {
    ...response
  }
}